package com.zmm.member.handler;

import com.zmm.common.dict.model.Region;
import com.zmm.common.mongo.key.member.RegionConstant;
import com.zmm.member.dao.DictDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author 900045
 * @description:
 * @name RegionHandler
 * @date By 2021-08-04 11:35:27
 */
@Slf4j
@Component
public class RegionHandler {

	@Resource
	private ThreadPoolExecutor threadPoolExecutor;
	

	@Resource
	private MongoTemplate mongoTemplate;

	@Resource
	private DictDao dictDao;
	

	/**
	 * 异步导入全部的区域信息
	 * @author: 900045
	 * @date: 2021-08-04 11:50:50
	 * @throws 
	
	 * @return: void
	 **/
	public void doSyncFromDb() {
		// 1. 清空原始数据
		mongoTemplate.dropCollection(RegionConstant.COLLECTION_REGION);
		log.info("清空数据中.....");
		List<Region> regionList = dictDao.selectAllRegion();
		
		if (!CollectionUtils.isEmpty(regionList)) {
			regionList.stream().forEach(region -> {
				region.setType(getType(region.getLevel()));
				CompletableFuture.runAsync(()->{
					mongoTemplate.insert(region, RegionConstant.COLLECTION_REGION);
				},threadPoolExecutor);
			});
		}
		log.info("导入数据完成!!!");
	}
	
	private String getType(Byte level){
		String type;
		switch (level){
			case 1:
				type = "省";
				break;
			case 2:
				type = "市";
				break;
			case 3:
				type = "区县";
				break;
			case 4:
				type = "街道";
				break;
				default:
					type = "未知";
					break;
		}
		return type;
	}
}
